import React,{useState,useEffect,useRef} from "react"
import { Button, Card , Form ,Table , Input ,Modal, notification,message} from 'antd'
import { PlusOutlined ,SearchOutlined ,DeleteOutlined,ExclamationCircleOutlined} from '@ant-design/icons'
import { getToken ,addKeyFn} from '../../utils/utils'
const {TextArea} = Input
import axios from 'axios'
function NewsList(){
    const [tableData,setTableData] = useState([])
    useEffect(()=>{
        axios.get('/my/news/newslist',{
            headers:{
                'Authorization':getToken()
            }
        }).then(res=>{
            const result = JSON.stringify(res.data.data)
            setTableData(addKeyFn(JSON.parse(result)))
        })
    },[])

    const [isShow,setIsShow] = useState(false)
    const [myForm] = Form.useForm()
    const addForm = useRef(null)


      // 删除操作
      const deleMethod =(item)=>{
        // 当前页面同步状态
        setTableData(tableData.filter(data=>data.newsId !== item.newsId))
        const newsId = item.newsId
        console.log(item)
        //要前后端同步
        axios.get('/my/news/delete/'+newsId,{
            headers:{'Authorization':getToken()}
        })
    }
    const confirmMethod=(item)=>{
        Modal.confirm({
            title: '您确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                console.log('ok')
                deleMethod(item);
                notification.info({
                message:'通知',
                description:'删除成功',
                placement:"bottomRight",
                });
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

     // 添加活动
     const addFormOk=()=>{
        addForm.current.validateFields().then(value=>{
            setIsShow(false)
            //从post到后端生成ID，方便删除和更新，自增长id
            axios({
                method:'post',
                url:'/my/news/add',
                headers:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization':getToken()
                },
                data:{ ...value}
            }).then(res=>{
              notification.info({
                message:'通知',
                description:res.data.message,
                placement:"bottomRight",
              });
            })
          }).catch(err=>{
            console.log(err)
          })
    }


     // 查询
     const [myform] = Form.useForm()
     // 搜索按钮事件
     const searchBtn = obj=>{
         console.log(obj)
         myform.setFieldsValue({newsTitle:''})
         if(obj.newsTitle === undefined){
             message.success('请输入新闻标题')
             return false
         }
         setTableData(tableData.filter(data=>data.newsTitle == obj.newsTitle))
         const newsTitle = obj.newsTitle
         // console.log(item)
         axios.get('/my/news/newslist/'+newsTitle,{
             headers:{'Authorization':getToken()}
         })
 
     }


    const columns = [
        {
            title:'新闻索引',
            key:'key',
            dataIndex:'key',
            render:(key)=>{
                return <b>{key}</b>
            }
            
        },{
            title:'图片',
            key:'cover_img',
            dataIndex:'cover_img',
            render:(cover_img)=>{
                return (
                    <img style={{width:"50px",height:'50px'}} src={cover_img}/>
                )
            }
            
        },{
            title:'新闻标题',
            key:'newsTitle',
            dataIndex:'newsTitle',
            render:(newsTitle)=>{
                return <b>{newsTitle}</b>
            }
            
        },{
            title:'新闻内容',
            key:'newsContent',
            dataIndex:'newsContent',
            render:(newsContent)=>{
                // return <TextArea rows={2} >{newsContent}</TextArea>
                return <b>{newsContent}</b>
            }
            
        },
        {
            title:'操作',
            key:'action',
            render:(item)=>{
                return <div>
                  <Button danger shape="circle" 
                    icon={<DeleteOutlined />}  
                    style={{marginRight:"10px"}}
                    onClick={()=>confirmMethod(item)}
                  />
                </div>
              }
        }
    ]
    return (
        <div>
            <Card
                title="新闻列表"
                extra={
                    <div>
                        <Button type="primary" 
                            icon={<PlusOutlined/>}
                            onClick={()=>{setIsShow(true)}}
                            style={{opacity:0.9,backgroundColor:"Highlight"}}
                        >添加新闻公告</Button>
                    </div>
                }  
            >
                <Form 
                    layout="inline"
                    form={myform}
                    onFinish={(n)=>{
                        searchBtn(n)
                    }}
                >
                    <Form.Item label='新闻标题' name='newsTitle'>
                        <Input placeholder="请输入要查询的新闻标题"/>
                    </Form.Item>
                    <Button htmlType="submit" type="primary" icon={<SearchOutlined />}></Button>  
                </Form>
                <Table 
                //    style={{overflow:"auto"}}
                    dataSource={tableData}
                    columns={columns}
                    pagination={{pageSize:3}} 
                    rowKey={record=>record.newsId}
                    >
                </Table>
            </Card>
            <Modal
                title="编辑输入框"
                open={isShow}
                maskClosable={false}
                onCancel={()=> setIsShow(false)}
                onOk={()=>{addFormOk()}}
            >
                <Form
                    ref={addForm}
                    form={myForm}
                    labelCol={{span:4}}
                    onFinish={(n)=>{
                        message.success('添加成功')
                    }}
                >
                    <Form.Item label='新闻标题' name='newsTitle' rules={[{required:true,message:'请输入新闻标题'}]}>
                        <TextArea rows={2} />
                    </Form.Item>
                    <Form.Item label='新闻内容' name='newsContent' rules={[{required:true,message:'请输入新闻内容'}]}>
                        <Input.TextArea placeholder="请输入新闻公告内容" />
                    </Form.Item>
                    <Form.Item label="图片地址" name="cover_pic" rules={[{ required: true, message: '请输入图片地址' }]}>
                        <Input placeholder="请输入图片链接" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}
export default NewsList